/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package edu.ipfw.cs590.cheat.struts.actions;

import edu.ipfw.cs590.cheat.AssignmentManagementInterface;
import edu.ipfw.cs590.cheat.AssignmentManagementService;
import edu.ipfw.cs590.cheat.GetPerson;
import edu.ipfw.cs590.cheat.RegisteredPerson;
import edu.ipfw.cs590.cheat.struts.actionforms.LoginForm;
import edu.ipfw.cs590.cheat.util.Authentication;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;

/**
 *
 * @author jmbaker
 */
public class LoginAction extends org.apache.struts.action.Action {

    private final static String SUCCESS = "LoginSuccess";
    private final static String FAILURE = "LoginFailure";

    /**
     * This is the action called from the Struts framework.
     * @param mapping The ActionMapping used to select this instance.
     * @param form The optional ActionForm bean for this request.
     * @param request The HTTP Request we are processing.
     * @param response The HTTP Response we are processing.
     * @throws java.lang.Exception
     * @return
     */
    @Override
    public ActionForward execute(ActionMapping mapping, ActionForm form,
            HttpServletRequest request, HttpServletResponse response)
            throws Exception {
        if (form instanceof LoginForm) {
            LoginForm lform = (LoginForm) form;

            //Get the user's session
            HttpSession session = request.getSession();

            try {
                // Call Web Service Operation
                edu.ipfw.cs590.cheat.AssignmentManagementService service = new edu.ipfw.cs590.cheat.AssignmentManagementService();
                edu.ipfw.cs590.cheat.AssignmentManagementInterface port = service.getAssignmentManagementSOAP();

                //Login
                String answer = port.login(lform.getEmail(), lform.getPassword());

                //If the login isn't failed
                if (answer != null) {
                    //Try parsing the int
                    int value = Integer.parseInt(answer);

                    //Calculate the access rights from the return of the token
                    int accessLevel =
                            Authentication.calculateAccessLevel(
                            port.getAccessRights(new edu.ipfw.cs590.cheat.GetAccessRights(), "" + value).getAccessRightsResult().getRights());

                    if (accessLevel > 0) {
                        //Get personal details
                        setPersonalDetails(session, lform.getEmail(), value);

                        //Create session
                        session.setAttribute(Authentication.SESSION_NAME_EMAIL, lform.getEmail());
                        System.out.println("Access Level: " + accessLevel);
                        session.setAttribute(Authentication.SESSION_NAME_RIGHTS, accessLevel);
                        session.setAttribute(Authentication.SESSION_NAME_TOKEN, "" + value);

                        return mapping.findForward(SUCCESS);
                    }
                }
            } catch (NumberFormatException exc) {
                //Do nothing
            } catch (Exception exc) {
                try {
                    session.invalidate();
                } catch (Exception exc2) {
                }

                //Something bad happened on the webservice side fail.
                ActionMessages errors = new ActionMessages();
                errors.add(ActionMessages.GLOBAL_MESSAGE,
                        new ActionMessage("errors.service.error", "Login", exc.getMessage()));
                this.saveErrors(request, errors);

                //Return failure.
                return mapping.getInputForward();
            }
        }

        //Create an action error
        ActionMessages errors = new ActionErrors();

        errors.add("InvalidLogin", new ActionMessage("errors.login.invalid"));

        // Report any errors
        if (!errors.isEmpty()) {
            //Save the errors
            saveErrors(request, errors);
            return new ActionForward(mapping.getInput());
        }

        //TODO insert erroring may want to extend the default ActionForm to one we always use with error handling in it.
        return mapping.findForward(FAILURE);
    }

    private void setPersonalDetails(HttpSession session, String email, int token) {
        // Call Web Service Operation
        AssignmentManagementService service = new AssignmentManagementService();
        AssignmentManagementInterface port = service.getAssignmentManagementSOAP();

        // Parameters
        GetPerson parameters = new GetPerson();
        parameters.setEMAIL(email);

        // Call operation
        RegisteredPerson rp = port.getPerson(parameters, "" + token).getPerson();

        //Set attributes
        session.setAttribute(Authentication.SESSION_NAME_FIRST_NAME, rp.getFirstName());
        session.setAttribute(Authentication.SESSION_NAME_LAST_NAME, rp.getLastName());
    }
}
